﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iLangl.Transport.Communication;
using iLangl.Model;
using iLangl.Security;
using System.IO;

namespace iLangl.BusinessModel.Managers
{
	public class PackageManager: BasePackageManager
	{
		public PackageManager() : base() { }
		public PackageManager(IPackageDAL packageDal) : base(packageDal) { }

		public override IPackage DispatchPackageFromFile(FileInfo packagefile)
		{
			IPackage package = base.DispatchPackageFromFile(packagefile);
			subscribeDispatchedPackage(package);
			return package;
		}

		public override IPackage DispatchPackageFromString(string packageContent)
		{
			IPackage package = base.DispatchPackageFromString(packageContent);
			subscribeDispatchedPackage(package);
			return package;
		}

		protected void subscribeDispatchedPackage(IPackage package)
		{
			//Package Authentication
			String sessionKey = package.SessionId;

			if (ManagerFacade.AuthenticationService.IsAuthenticated(sessionKey))
			{
				String userName = ManagerFacade.AuthenticationService.GetUserName(sessionKey);

				
				String contactId = AuthenticationManager.Instance.ReadContactIdByUserAccount(userName);

				Contact contact = ContactManager.Instance.GetContact(contactId);

				if (contact != null)
				{
					package.ContactId = contact.Id;

					if(contact.Company != null)
						package.CompanyId = contact.Company.Id;
				}

			}
			else
			{
				ManagerFacade.PackageManager.PackageNotAuthenticated(package);

				Facade.Instance.AlertManager.RaiseAlert(
				new ApplicationException(
					string.Format("Authentication is failed for package with Id='{0}'", package.Id)));

			}

		}
	}
}
